package com.papercutting.platform.util;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全工具类
 */
@Component
public class SecurityUtils {
    
    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            
            // 临时调试信息
            System.out.println("=== SecurityUtils Debug ===");
            System.out.println("请求URL: " + request.getRequestURL());
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("Authorization头: " + request.getHeader("Authorization"));
            
            String token = getTokenFromRequest(request);
            if (token == null) {
                System.out.println("错误: 未找到有效的认证令牌");
                throw new RuntimeException("未找到有效的认证令牌");
            }
            
            System.out.println("提取的Token前20字符: " + token.substring(0, Math.min(20, token.length())) + "...");
            
            // 从Spring容器中获取JwtUtil实例
            JwtUtil jwtUtil = SpringContextUtil.getBean(JwtUtil.class);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                System.out.println("错误: 无法从令牌中获取用户ID");
                throw new RuntimeException("无法从令牌中获取用户ID");
            }
            
            System.out.println("解析得到的用户ID: " + userId);
            return userId;
        } catch (Exception e) {
            System.out.println("获取当前用户ID异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("获取当前用户ID失败: " + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取token
     */
    private static String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
    
    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            
            String token = getTokenFromRequest(request);
            if (token == null) {
                return null;
            }
            
            JwtUtil jwtUtil = SpringContextUtil.getBean(JwtUtil.class);
            return jwtUtil.getUsernameFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }
}
